<template>
  <view class="customer-service-page">
    <!-- 顶部信息卡片 -->
    <view class="info-card">
      <view class="card-header">
        <image class="header-icon" src="/static/logo/512.png" mode="aspectFit"></image>
        <text class="header-title">扫码联系客服专员</text>
      </view>
      <text class="card-subtitle">使用微信或其他扫码工具扫描下方二维码，即可与我们的客服专员取得联系</text>
    </view>

    <!-- 步骤说明 -->
    <view class="steps-card">
      <view class="step-item">
        <view class="step-number">1</view>
        <text class="step-text">打开扫码工具</text>
      </view>
      <view class="step-divider">
        <uv-icon name="arrow-down" size="20" color="#00d4aa"></uv-icon>
      </view>
      <view class="step-item">
        <view class="step-number">2</view>
        <text class="step-text">扫描二维码</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-wrapper">
      <uv-loading-icon mode="circle" size="40"></uv-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 二维码列表 -->
    <view v-else-if="qrcodeList.length > 0" class="qrcode-list">
      <view class="qrcode-card" v-for="(item, index) in qrcodeList" :key="index">
        <text class="qrcode-title">客服专线</text>

        <view class="qrcode-wrapper">
          <image
            :id="'qrcodeImage' + index"
            class="qrcode-image"
            :src="item"
            mode="aspectFit"
            @longpress="saveQRCode(item, index)"
          ></image>
        </view>

        <!-- 保存按钮 -->
        <view class="save-btn-wrapper">
          <view class="save-btn" @click="saveQRCode(item, index)">
            <uv-icon name="download" size="18" color="#ffffff"></uv-icon>
            <text class="save-btn-text">保存二维码</text>
          </view>
        </view>

        <text class="qrcode-tip">点击按钮保存二维码或使用微信扫一扫</text>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-else class="empty-wrapper">
      <uv-icon name="info-circle" size="80" color="#ccc"></uv-icon>
      <text class="empty-text">暂无客服二维码</text>
    </view>
  </view>
</template>

<script>
import { getCustomerQrCodeList } from '@/api/customer'

export default {
  name: 'CustomerService',
  data() {
    return {
      qrcodeList: [], // 二维码列表
      loading: false, // 加载状态
      currentQrcodePath: '' // 当前操作的二维码路径
    }
  },

  onLoad() {
    this.loadQrcodeList()
  },

  methods: {
    /**
     * 加载客服二维码列表
     */
    async loadQrcodeList() {
      try {
        this.loading = true
        const response = await getCustomerQrCodeList()
        console.log('客服二维码列表:', response)

        if (response.code === 200 && response.data) {
            this.qrcodeList = response.data
            console.log('客服二维码列表:', this.qrcodeList)
        } else {
          console.error('获取客服二维码列表失败:', response.message)
          uni.showToast({
            title: response.message || '获取二维码失败',
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        console.error('加载客服二维码列表失败:', error)
        uni.showToast({
          title: '加载失败，请稍后重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
      }
    },

    /**
     * 保存二维码到相册
     * @param {string} imagePath - 二维码图片路径
     * @param {number} index - 二维码索引
     */
    async saveQRCode(imagePath, index) {
      try {
        this.currentQrcodePath = imagePath

        // #ifdef H5
        // H5 环境：使用 canvas 转换图片并下载
        await this.saveQRCodeForH5()
        // #endif

        // #ifndef H5
        // App 和小程序环境：保存到相册
        await this.saveQRCodeForApp()
        // #endif
      } catch (error) {
        console.error('保存二维码失败:', error)
        uni.showToast({
          title: '保存失败',
          icon: 'none',
          duration: 2000
        })
      }
    },

    /**
     * H5 环境保存二维码 - 使用 Canvas 方式
     */
    async saveQRCodeForH5() {
      // #ifdef H5
      return new Promise((resolve, reject) => {
        try {
          uni.showLoading({
            title: '保存中...',
            mask: true
          })

          const imagePath = this.currentQrcodePath
          const timestamp = Date.now()
          const filename = `qrcode_${timestamp}.png`

          // 方案1：尝试使用 Canvas 方式
          this.downloadImageViaCanvas(imagePath, filename)
            .then(() => {
              uni.hideLoading()
              uni.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              })
              resolve()
            })
            .catch((canvasError) => {
              console.warn('Canvas 方式失败，尝试直接下载:', canvasError)

              // 方案2：如果 Canvas 失败，尝试直接下载
              this.downloadImageDirect(imagePath, filename)
                .then(() => {
                  uni.hideLoading()
                  uni.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                  resolve()
                })
                .catch((directError) => {
                  console.error('直接下载也失败:', directError)
                  uni.hideLoading()

                  // 方案3：提示用户手动保存
                  uni.showToast({
                    title: '请长按图片选择"图片另存为"',
                    icon: 'none',
                    duration: 3000
                  })
                  resolve()
                })
            })
        } catch (error) {
          console.error('H5 保存异常:', error)
          uni.hideLoading()
          reject(error)
        }
      })
      // #endif
    },

    /**
     * 通过 Canvas 下载图片
     */
    downloadImageViaCanvas(imagePath, filename) {
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.crossOrigin = 'anonymous'

        img.onload = () => {
          try {
            const canvas = document.createElement('canvas')
            canvas.width = img.width
            canvas.height = img.height
            const ctx = canvas.getContext('2d')
            ctx.drawImage(img, 0, 0)

            canvas.toBlob((blob) => {
              if (blob) {
                const url = window.URL.createObjectURL(blob)
                const link = document.createElement('a')
                link.href = url
                link.download = filename
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
                window.URL.revokeObjectURL(url)
                resolve()
              } else {
                reject(new Error('Canvas toBlob failed'))
              }
            }, 'image/png')
          } catch (error) {
            reject(error)
          }
        }

        img.onerror = () => {
          reject(new Error('Image load failed'))
        }

        img.src = imagePath
      })
    },

    /**
     * 直接下载图片
     */
    downloadImageDirect(imagePath, filename) {
      return new Promise((resolve, reject) => {
        fetch(imagePath, {
          mode: 'cors',
          credentials: 'omit'
        })
          .then(response => {
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`)
            }
            return response.blob()
          })
          .then(blob => {
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = filename
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    /**
     * App 和小程序环境保存二维码
     */
    async saveQRCodeForApp() {
      // #ifndef H5
      return new Promise((resolve, reject) => {
        try {
          uni.showLoading({
            title: '保存中...',
            mask: true
          })

          const imagePath = this.currentQrcodePath
          console.log('开始保存图片，路径:', imagePath)

          // 判断是否是网络图片
          if (imagePath.startsWith('http')) {
            console.log('检测到网络图片，开始下载')
            this.downloadAndSaveImage(imagePath)
              .then(() => {
                uni.hideLoading()
                resolve()
              })
              .catch((err) => {
                uni.hideLoading()
                console.error('网络图片保存失败:', err)
                uni.showToast({
                  title: '保存失败，请重试',
                  icon: 'none',
                  duration: 2000
                })
                reject(err)
              })
          } else {
            // 本地图片，直接保存
            console.log('检测到本地图片，直接保存')
            this.saveLocalImage(imagePath)
              .then(() => {
                uni.hideLoading()
                resolve()
              })
              .catch((err) => {
                uni.hideLoading()
                console.error('本地图片保存失败:', err)
                uni.showToast({
                  title: '保存失败，请重试',
                  icon: 'none',
                  duration: 2000
                })
                reject(err)
              })
          }
        } catch (error) {
          console.error('App 保存异常:', error)
          uni.hideLoading()
          reject(error)
        }
      })
      // #endif
    },

    /**
     * 保存本地图片到相册
     */
    saveLocalImage(imagePath) {
      return new Promise((resolve, reject) => {
        // 先获取图片信息，确保路径有效
        uni.getImageInfo({
          src: imagePath,
          success: (imageInfo) => {
            console.log('本地图片信息:', imageInfo)

            // 保存图片到相册
            uni.saveImageToPhotosAlbum({
              filePath: imageInfo.path,
              success: () => {
                console.log('本地图片保存成功')
                uni.showToast({
                  title: '保存成功',
                  icon: 'success',
                  duration: 2000
                })
                resolve()
              },
              fail: (err) => {
                console.error('保存本地图片失败:', err)
                const errMsg = err.errMsg || ''

                // 检查是否是权限问题
                if (errMsg.includes('auth') || errMsg.includes('permission') || errMsg.includes('denied')) {
                  uni.showToast({
                    title: '需要相册权限，请在设置中开启',
                    icon: 'none',
                    duration: 3000
                  })
                  // 延迟后打开设置
                  setTimeout(() => {
                    uni.openSetting()
                  }, 1000)
                  resolve()
                } else {
                  reject(err)
                }
              }
            })
          },
          fail: (err) => {
            console.error('获取本地图片信息失败:', err)
            reject(err)
          }
        })
      })
    },

    /**
     * 下载网络图片并保存到相册
     */
    downloadAndSaveImage(imageUrl) {
      return new Promise((resolve, reject) => {
        console.log('开始下载网络图片:', imageUrl)

        uni.downloadFile({
          url: imageUrl,
          success: (res) => {
            console.log('图片下载结果:', res.statusCode)

            if (res.statusCode === 200) {
              console.log('图片下载成功，临时路径:', res.tempFilePath)

              // 保存下载的图片到相册
              uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: () => {
                  console.log('网络图片保存成功')
                  uni.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                  resolve()
                },
                fail: (err) => {
                  console.error('保存下载的图片失败:', err)
                  const errMsg = err.errMsg || ''

                  // 检查是否是权限问题
                  if (errMsg.includes('auth') || errMsg.includes('permission') || errMsg.includes('denied')) {
                    uni.showToast({
                      title: '需要相册权限，请在设置中开启',
                      icon: 'none',
                      duration: 3000
                    })
                    // 延迟后打开设置
                    setTimeout(() => {
                      uni.openSetting()
                    }, 1000)
                    resolve()
                  } else {
                    reject(err)
                  }
                }
              })
            } else {
              console.error('图片下载失败，状态码:', res.statusCode)
              reject(new Error(`Download failed with status ${res.statusCode}`))
            }
          },
          fail: (err) => {
            console.error('下载图片请求失败:', err)
            reject(err)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.customer-service-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 32rpx;
}

// 顶部信息卡片
.info-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 40rpx 32rpx;
  margin-bottom: 24rpx;
  
  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    
    .header-icon {
      width: 64rpx;
      height: 64rpx;
      margin-right: 20rpx;
      border-radius: 12rpx;
    }
    
    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .card-subtitle {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }
}

// 步骤卡片
.steps-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .step-number {
      width: 64rpx;
      height: 64rpx;
      line-height: 64rpx;
      text-align: center;
      background: #00d4aa;
      border-radius: 50%;
      color: #fff;
      font-size: 32rpx;
      font-weight: 600;
      margin-bottom: 16rpx;
    }
    
    .step-text {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }
  
  .step-divider {
    margin: 0 60rpx;
    margin-bottom: 50rpx;
  }
}

// 加载状态
.loading-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;

  .loading-text {
    margin-top: 24rpx;
    font-size: 28rpx;
    color: #999;
  }
}

// 空状态
.empty-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;

  .empty-text {
    margin-top: 24rpx;
    font-size: 28rpx;
    color: #999;
  }
}

// 二维码列表
.qrcode-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

// 二维码卡片
.qrcode-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 40rpx 32rpx;

  .qrcode-title {
    display: block;
    text-align: center;
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 32rpx;
  }

  .qrcode-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 32rpx;
    background: #f8f9fa;
    border-radius: 16rpx;
    margin-bottom: 24rpx;

    .qrcode-image {
      width: 500rpx;
      height: 500rpx;
      border-radius: 12rpx;
      background: #fff;
    }
  }

  .qrcode-tip {
    display: block;
    text-align: center;
    font-size: 24rpx;
    color: #999;
    line-height: 1.5;
  }

  .save-btn-wrapper {
    display: flex;
    justify-content: center;
    margin-bottom: 24rpx;
  }

  .save-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx 48rpx;
    background: linear-gradient(135deg, #00d4aa 0%, #00b894 100%);
    border-radius: 48rpx;
    cursor: pointer;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
    }

    .save-btn-text {
      margin-left: 12rpx;
      font-size: 28rpx;
      font-weight: 500;
      color: #ffffff;
    }
  }
}
</style>

